﻿using Microsoft.AspNetCore.Mvc;
using Rbac.Api.Dto;
using Rbac.Api.ServiceInterface;

namespace Rbac.Api.Controllers
{
    [ApiController]
    [Route("api/permission")]
    public class PermissionController : ControllerBase
    {
        public IPermissionService PermissionService { get; }

        public PermissionController(IPermissionService permissionService)
        {
            PermissionService = permissionService;
        }


        [HttpGet("{id}")]
        public async Task<IActionResult> GetPermissionById(int id)
        {
            var permission = await PermissionService.GetPermissionByIdAsync(id);
            if (permission == null)
            {
                return NotFound();
            }
            return Ok(permission);
        }

        [HttpGet("all")]
        public async Task<IActionResult> GetAllPermissions()
        {
            var permissions = await PermissionService.GetAllPermissionsAsync();
            return Ok(permissions);
        }


        [HttpPost]
        public async Task<IActionResult> CreatePermission([FromBody] CreatePermissionDto createDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var permission = await PermissionService.CreatePermissionAsync(createDto);
            return CreatedAtAction(nameof(GetPermissionById), new { id = permission.Id }, permission);
        }


        [HttpPut]
        public async Task<IActionResult> UpdatePermission([FromBody] UpdatePermissionDto updateDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var result = await PermissionService.UpdatePermissionAsync(updateDto);
            if (!result)
            {
                return NotFound();
            }
            return NoContent();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> DeletePermission(int id)
        {
            var result = await PermissionService.DeletePermissionAsync(id);
            if (!result)
            {
                return NotFound();
            }
            return NoContent();
        }

    }
}
